package com.a2j.exception;

import com.a2j.beans.base.BaseBean;
import com.a2j.beans.base.code.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Author: bzb
 * Data: 2021/8/25 23:04
 * Desc: 全局异常捕获
 */
@Slf4j // log
@ControllerAdvice
public class GlobalException {

    @ResponseBody // 处理返回
    @ExceptionHandler(Exception.class)
    public BaseBean<String> exception(Exception e) {
        log.error("全局异常：", e);
        return BaseBean.failed("全局异常：" + e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(NullPointerException.class)
    public BaseBean<String> exception(NullPointerException e) {
        log.error("空指针异常：", e);
        return BaseBean.failed(ResponseCode.UNKNOWN_ERROR);
    }

    @ResponseBody
    @ExceptionHandler(IllegalArgumentException.class)
    public BaseBean<String> exception(IllegalArgumentException e) {
        log.error("参数异常：", e);
        return BaseBean.failed(ResponseCode.FAILED.getCode(), e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(BizException.class)
    public BaseBean<String> exception(BizException e) {
        log.error("业务异常：" + e.getMessage(), e);
        return BaseBean.failed(e.errorCode, e.errorMessage);
    }
}
